<template>
  <div class="cutter-purchase full-height bg-white page-content content relative-position padding-r-20 padding-l-20">
    <collapse ref="collapse">
      <template v-slot:content>
        <div class="form-inline justify-between form-inline bottom" style="padding: 4px 0 0">
          <div class="left box flex">
            <div class="margin-r-20 margin-b-20">
              <span class="font-size-16" style="padding-right: 6px">选择月份:</span>
              <date-picker
                format="YYYY-MM"
                :editable="false"
                type="month" v-model="params.dateRange"
                range placeholder="请选择月份范围"
                style="width: 180px"
              />
            </div>
            <q-input
              v-model.trim="params.number"
              class="margin-b-20 margin-r-20"
              dense
              outlined
              placeholder="请输入采购单号"
            >
              <template v-slot:before>
                <label class="text-right font-size-16 text-black">
                  <span>采购单号:</span>
                </label>
              </template>
            </q-input>
          </div>
          <div class="flex no-wrap">
            <q-btn
              class="btn margin-r-10"
              outline dense emit-value map-options options-dense
              color="primary"
              @click="resetSearch()"
              label="重置"
            />
            <q-btn class="btn" unelevated type="submit" color="primary" label="查询" @click="searchData()" />
          </div>
        </div>
        <div class="form-inline bottom" style="padding: 0 0 16px">
          <export-btn
            :disable="!tableData.length"
            :exportFun="exportFun"
            :exportParams="exportParams"
            :exportName="getExportName()"/>
        </div>
      </template>
    </collapse>
    <q-table :data="tableData"
             :columns="tableColumns"
             row-key="id"
             class="myTable scroll"
             style="margin: 4px 0 62px"
             :pagination.sync="pagination"
             :hide-bottom="tableData.length !== 0"
             :loading="isTableLoading"
             color="primary">
      <template v-slot:header-cell-purchaseDate="props">
        <q-th :props="props"
              class="sortable"
              :class="[sortBy == 'purchaseDate' ? 'sorted' : '','sort-' +value]"
              @click="sortable('purchaseDate')">
          {{ props.col.label }}
          <q-icon name="arrow_upward"
                  size="16px"
                  class="q-table__sort-icon" />
        </q-th>
      </template>
      <template v-slot:bottom-row>
        <total-row :data="totalRow" v-if="tableData.length"/>
      </template>
    </q-table>
    <pagination v-model="pagination.page"
                :page-size="pagination.rowsPerPage"
                :total="pagination.rowsNumber"
                @changePageSize="onPageSizeChange"
                @changePage="onPageChange"
                style="margin-bottom: 20px" />
  </div>
</template>

<script>
import _ from 'lodash'
import moment from 'moment'
import Pagination from '../../components/pagination/index'
import Collapse from 'src/components/collapse'
import TotalRow from './components/total-row'
import cutterReport from 'src/boot/statistics/cutter-report'

export default {
  name: 'cutter-purchase',
  components: {
    Pagination,
    Collapse,
    TotalRow
  },
  data () {
    return {
      tableData: [],
      isDisable: false, // 导出按钮禁用
      params: {
        dateRange: [null, null],
        number: ''
      },
      exportFun: cutterReport.exportPurchaseList,
      tableColumns: [
        { name: 'number', label: '采购单号', field: 'number', align: 'left' },
        { name: 'sku', label: 'SKU', field: 'sku', align: 'left' },
        { name: 'totalQuantity', label: '采购数量', field: 'totalQuantity', align: 'left' },
        { name: 'taxRate', label: '税率', field: 'taxRate', align: 'left' },
        { name: 'totalPriceTax', label: '含税总价', field: 'totalPriceTax', align: 'left' },
        { name: 'buyerName', label: '采购员', field: 'buyerName', align: 'left' },
        { name: 'purchaseDate', label: '采购日期', field: 'purchaseDate', align: 'left' }
      ],
      exportParams: {}, // 请求数据
      // 表格分页配置
      pagination: {
        // 当前页码
        page: 1,
        // 每页条数
        rowsPerPage: 15,
        // 总条数
        rowsNumber: 0
      },
      // 排序字段
      sortBy: '',
      // 排序（正序/倒序）
      value: '',
      // 表格正在加载
      isTableLoading: false,
      totalRow: [
        {
          label: '含税总价',
          value: '15863.15'
        }
      ]
    }
  },
  created () {
    this.getList()
  },
  methods: {
    // 获取列表
    getList () {
      this.isTableLoading = true
      const params = {}
      !_.isEmpty(this.params.number) && (params['number'] = this.params.number)
      !_.isNil(this.params.dateRange[0]) && (params['startDate'] = moment(this.params.dateRange[0]).format('YYYY-MM-DD'))
      !_.isNil(this.params.dateRange[1]) && (params['endDate'] = moment(this.params.dateRange[1]).format('YYYY-MM-DD'))
      !_.isEmpty(this.value) && (params['purchaseDateAsc'] = this.value === 'asc')
      this.exportParams = _.cloneDeep(params)
      params['pageNum'] = this.pagination.page
      params['pageSize'] = this.pagination.rowsPerPage
      cutterReport.getPurchaseList(params).then(res => {
        if (res.page.records.length) {
          res.page.records.forEach(item => {
            if ((item.totalPriceTax + '').indexOf('.') !== -1) {
              console.log(item.totalPriceTax + '', 111)
              const totalPriceTax = (item.totalPriceTax + '').split('.')
              let float = Math.round(totalPriceTax[1] / 100)
              !float && (float = '00')
              item.totalPriceTax = `${totalPriceTax[0]}.${float}`
            } else {
              item.totalPriceTax = item.totalPriceTax + '.00'
            }
            item.purchaseDate = moment(item.purchaseDate).format('YYYY-MM-DD')
          })
        }
        this.tableData = res.page.records
        if ((res.totalPrice + '').indexOf('.') !== -1) {
          const totalPrice = (res.totalPrice + '').split('.')
          let float = Math.round(totalPrice[1] / 100)
          !float && (float = '00')
          this.totalRow[0].value = `${totalPrice[0]}.${float}`
        } else {
          this.totalRow[0].value = res.totalPrice + '.00'
        }
        this.pagination.rowsNumber = res.page.total

        this.isTableLoading = false
      }).catch(res => {
        console.log(res)
        this.isTableLoading = false
      })
    },
    /**
     * 重置查询条件
     */
    resetSearch () {
      this.params = {
        dateRange: [null, null],
        number: ''
      }
    },
    // 搜索
    searchData () {
      if (this.params.dateRange && Math.abs(moment(this.params.dateRange[0]).diff(moment(this.params.dateRange[1]), 'months')) > 24) {
        this.$q.dialog({
          title: `<p class="dialog-notice-title"><i class="iconfont icontubiao-28"></i>所选月范围不可超出24月</p>`,
          html: true,
          ok: {
            unelevated: true,
            label: '确认'
          }
        })
        return false
      }
      // 查询
      this.pagination.page = 1
      this.getList()
    },
    // 表格排序
    sortable (type) {
      this.tableData = []
      if (this.sortBy === type) {
        if (this.value) {
          this.value = this.value === 'asc' ? 'desc' : 'asc'
        } else {
          this.value = 'asc'
        }
      } else {
        this.sortBy = type
        this.value = 'asc'
      }
      this.pagination.page = 1
      this.getList()
    },
    // 获取导出报表名称
    getExportName () {
      let name = '刀具采购报表'
      !_.isNil(this.exportParams.startDate) && (name += `_${moment(this.exportParams.startDate).format('YYYY-MM')}`)
      !_.isNil(this.exportParams.endDate) && (name += `_${moment(this.exportParams.endDate).format('YYYY-MM')}`)
      name += '.xls'
      return name
    },
    /**
     * on 分页组件的每页条数发生改变
     * @param val 每页条数
     */
    onPageSizeChange: function (val, page) {
      this.pagination.rowsPerPage = val
      page && (this.pagination.page = page)
      this.getList()
    },

    /**
     * on 分页组件的页码发生改变
     * @param val 页码
     */
    onPageChange: function (val) {
      this.pagination.page = val
      this.getList()
    }
  }
}
</script>

<style scoped lang="stylus">

</style>
